Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix expand hasMany relationship #1542

Open
wants to merge 1 commit into
base: v0
Choose a base branch
from
Open

Conversation

flashios09
Copy link

The _expand query param would work with a belongsTo relationship but not with hasMany relationship.

For this db.json:

{
  "posts": [{
     "id": 1,
     "title": "My post title",
     "userId": 2,
     "tags": [1, 2]
  }],
  "users": [...],
  "tags": [...]
}

This posts/3?_expand=user work since the post has a userId foreign key as "userId" : 2, it's just a belongsTo relationship, but posts/3?_expand=tags will not work since it will look for tagsId property inside the post, and deal with the value as a number not number[], so expect "tagsId": n not "tagsId": [x, y, z].

Updating the expand function fixes this issue, now it will check first if the key exists in the resource, so check first for "tags" before tagsId, means before adding the Id suffix:

 const prop = Object.keys(resource).includes(innerResource) 
   ? innerResource 
   : `${innerResource}${opts.foreignKeySuffix}`;

Then check if its value is an array, e.g. "tags": [1, 2]

resource[innerResource] = (Array.isArray(resource[prop]))
  // `"tags": [1, 2]`
  ? resource[prop].reduce((acc, id) => [...acc, db.get(plural).getById(id).value()], [])
  // `"userId": 2`
  : resource[innerResource] = db.get(plural).getById(resource[prop]).value();

@flashios09 flashios09 closed this Apr 28, 2024
@flashios09 flashios09 reopened this Apr 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants